<template>
  <div class="container">
    <div class="app-container">
      <!-- 组织架构 -->
      <el-tree default-expand-all :data="depts" :props="defaultProps">
        <!-- 节点结构 -->
        <!-- v-slot="{ node, data }" 只能作用在template -->
        <template v-slot="{ data }">
          <el-row style="width:100%;height:40px" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <!-- $event 实参 表示类型 -->
              <el-dropdown @command="handleCommand($event,data.id)">
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
      <el-dialog :visible.sync="showDialog" :title="title" @close="handleClose">
        <el-form ref="addDept" label-width="120px" :rules="rules" :model="formData">
          <el-form-item prop="name" label="部门名称">
            <el-input v-model="formData.name" placeholder="2-10个字符" style="width: 80%" size="mini" />
          </el-form-item>
          <el-form-item prop="code" label="部门编码">
            <el-input v-model="formData.code" placeholder="2-10个字符" style="width: 80%" size="mini" />
          </el-form-item>
          <el-form-item prop="managerId" label="部门负责人">
            <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width: 80%" size="mini">
              <!-- 下拉选项 循环 负责人数据 label表示显示的字段 value 存储字段 -->
              <el-option
                v-for="item in ManagerList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="introduce" label="部门介绍">
            <el-input v-model="formData.introduce" placeholder="1-100个字符" type="textarea" size="mini" :rows="4" style="width: 80%" />
          </el-form-item>
        </el-form>
        <div style="display: flex;justify-content: center;">
          <el-button type="primary" @click="btnOK">确定</el-button>
          <el-button @click="close">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { transLate2TreeData } from '@/utils'
import { getManagerList, editDepartment, addDepartments, getdepartments, getDepartDetail, deleteDepartment } from '@/api/department'
export default {
  name: 'Department',
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      message: '',
      showDialog: false,
      formData: {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        managerId: '', // 部门负责人id
        name: '', // 部门名称
        pid: '' // 父级部门的id
      },
      ManagerList: [], // 存储负责人列表
      rules: {
        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 2, max: 10, message: '部门编码的长度为2-10个字符', trigger: 'blur'
          },
          {
            trigger: 'blur',
            // 自定义校验模式
            validator: async(rule, value, callback) => {
              // value就是输入的编码
              let result = await getdepartments()
              if (this.formData.id) {
                // 编辑场景
                result = result.filter(item => item.id !== this.formData.id)
              }
              // result数组中是否存在 value值
              if (result.some(item => item.code === value)) {
                callback(new Error('部门中已经有该编码了'))
              } else {
                callback()
              }
            }
          }
        ], // 部门编码
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' }, {
          min: 1, max: 100, message: '部门介绍的长度为1-100个字符', trigger: 'blur'
        }], // 部门介绍
        managerId: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }], // 部门负责人id
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 2, max: 10, message: '部门名称的长度为2-10个字符', trigger: 'blur'
          },
          {
            trigger: 'blur',
            // 自定义校验模式
            validator: async(rule, value, callback) => {
            // value就是输入的编码
              let result = await getdepartments()
              if (this.formData.id) {
                // 编辑场景 排除自身
                result = result.filter(item => item.id !== this.formData.id)
              }
              // result数组中是否存在 value值
              if (result.some(item => item.name === value)) {
                callback(new Error('部门中已经有该名称了'))
              } else {
                callback()
              }
            }
          }] // 部门名称
        // pid: '' // 父级部门的id 不需要做校验
      },
      parentId: '' // 父级部门的id 不需要做校验
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getdepartments()
  },
  methods: {
    async getdepartments() {
      const result = await getdepartments()
      // console.log(result)
      // console.log('传智教育', this.getChildrenDepart(result, 1))
      // this.depts = this.getChildrenDepart(result, 0)
      this.depts = transLate2TreeData(result, 0)
    },
    handleCommand(command, id) {
      if (command === 'add') {
        this.showDialog = true
        this.parentId = id // 父级id
        this.getManagerList()
      }
      if (command === 'edit') {
        this.showDialog = true
        // 存储自己的id
        this.parentId = id
        this.getDepartDetail()
        this.getManagerList()
      }
      if (command === 'del') {
        // 删除
        this.parentId = id
        // this.deleteDepartment()
        this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '我再想想',
          type: 'warning'
        }).then(async() => {
          await this.deleteDepartment()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    async deleteDepartment() {
      await deleteDepartment(this.parentId)
      this.$message.success('删除成功')
      this.getdepartments()
    },
    async getDepartDetail() {
      const result = await getDepartDetail(this.parentId)
      // console.log(result)
      this.formData = result
    },
    // 获取部门负责人
    async getManagerList() {
      this.ManagerList = await getManagerList()
      // console.log(this.ManagerList)
    },
    // 点击确定时调用
    btnOK() {
      this.$refs.addDept.validate(async isOK => {
        if (isOK) {
          let msg = '新增'
          if (this.formData.id) {
            msg = '编辑'
            await editDepartment(this.formData)
          } else {
            await addDepartments({ ...this.formData, pid: this.parentId })
          }
          // 关闭弹层
          this.showDialog = false
          this.handleClose()
          // 提示消息
          this.$message.success(`${msg}部门成功`)
          this.getdepartments()
          this.close()
        }
      })
    },
    close() {
      this.$refs.addDept.resetFields() // 重置表单
      // 关闭弹层
      this.showDialog = false
    },
    handleClose() {
      this.$refs.addDept.resetFields()
      this.formData = {
        name: '', // 部门名称
        code: '',
        managerId: '',
        introduce: '' // 部门介绍
      }
    }
    // getChildrenDepart(list, departId) {
    //   const arr = []
    //   list.forEach(item => {
    //     if (item.pid === departId) {
    //       item.children = this.getChildrenDepart(list, item.id)
    //       arr.push(item)
    //     }
    //   })
    //   return arr
    // }
  }
}
</script>

<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
.el-dropdown-link {
  color: #409eff;
  cursor: pointer;
}
</style>
